package cn.qingyun.gis.modules.handle;

import cn.qingyun.gis.exception.CommonException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.TypeHandler;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.OTHER)
public class JsonbToEntityHandler<T> implements TypeHandler<T> {
    private static final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    private final Class<T> aClass;

    public JsonbToEntityHandler(Class<T> aClass) {
        this.aClass = aClass;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        try {
            synchronized (this) {
                PGobject jsonObject = new PGobject();
                String jsonString = objectMapper.writeValueAsString(parameter);
                jsonObject.setValue(jsonString);
                jsonObject.setType("jsonb");
                ps.setObject(i, jsonObject);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error1 converting object to JSONB", e);
        }
    }

    @Override
    public T getResult(ResultSet rs, String columnName) {
        try {
            synchronized (this) {
                if (StringUtils.isEmpty(rs.getString(columnName))) {
                    return null;
                }
                return objectMapper.readValue(rs.getString(columnName), aClass);
            }
        } catch (Exception e) {
            throw new CommonException("Error2 converting JSONB to object", e);
        }
    }

    @Override
    public T getResult(ResultSet rs, int columnIndex) {
        try {
            synchronized (this) {
                if (StringUtils.isEmpty(rs.getString(columnIndex))) {
                    return null;
                }
                return objectMapper.readValue(rs.getString(columnIndex), aClass);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error3 converting JSONB to object", e);
        }
    }

    @Override
    public T getResult(CallableStatement cs, int columnIndex) {
        try {
            synchronized (this) {
                if (StringUtils.isEmpty(cs.getString(columnIndex))) {
                    return null;
                }
                return objectMapper.readValue(cs.getString(columnIndex), aClass);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error4 converting JSONB to object", e);
        }
    }
}